<template>
  <div class="bdMap" ref="map" tabindex="-1" :style="mapStyle"></div>
</template>

<script>
import Map from './libs/Map';

export default {
  name: 'bdMap',
  inheritAttrs: false,
  props: {
    options: Object,
  },
  data() {
    return {
      loaded: false,
    };
  },
  computed: {
    mapStyle() {
      return { visibility: this.loaded ? 'visible' : 'hidden' };
    },
  },
  mounted() {
    this.initMap();
    this.initEvent();
  },
  beforeDestroy() {
    // 解绑地图事件
    if (this.$refs.map) {
      this.$refs.map.removeEventListener('keyup', this.handleKeyEvent, false);
    }
    // 销毁地图实例
    if (this.map) {
      this.map.off('tilesloaded', this.loadedEmit);
      this.map.destroy();
    }
  },
  methods: {
    /**
     * 初始化地图
     */
    async initMap() {
      const map = new Map(this.$refs.map, { ...this.options });
      map.on('loaded', this.mapLoaded);
      map.init();
    },

    /**
     * @description: 地图加载回调
     * @param {*} map
     * @return {*}
     */
    mapLoaded(map) {
      this.map = map;
      const { disableControl, useTilesLoaded } = this.options || {};

      // 添加控件
      if (!disableControl) {
        let resetCtrl = new BMapGL.ResetControl();
        map.addControl(resetCtrl);
        let zoomCtrl = new BMapGL.ZoomControl();
        map.addControl(zoomCtrl);
      }

      // 处理加载完成
      if (!useTilesLoaded) {
        this.loadedEmit();
      } else {
        map.on('tilesloaded', this.loadedEmit);
      }
    },

    /**
     * @description: 加载完成派发
     * @return {*}
     */
    loadedEmit() {
      if (this.loaded) return;
      this.loaded = true;
      this.$emit('loaded', this.map);
    },

    /**
     * @description: 初始化事件
     * @return {*}
     */
    initEvent() {
      this.$refs.map.addEventListener('keyup', this.handleKeyEvent, false);
    },

    /**
     * @description: 处理键盘事件
     * @param {*} keyCode
     * @return {*}
     */
    handleKeyEvent({ keyCode }) {
      // 空格键复位
      if (keyCode === 32 && this.map) {
        this.map.viewportReset();
      }
    },
  },
};
</script>

<style scoped lang="scss">
.bdMap {
  width: 100%;
  height: 100%;
  background-image: none !important; // 防止在暗色背景下出现白线
}
</style>

<style lang="scss">
.anchorBL {
  display: none;
}

.BMap_stdMpReset {
  position: absolute;
  inset: auto 15px 20px auto;
  z-index: 10;
  background: rgb(255, 255, 255);
  box-shadow: rgba(107, 120, 137, 0.2) 0 2px 6px 0, rgba(91, 98, 107, 0.08) 0 4px 10px 0;

  .BMap_button_new {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 26px;
    height: 26px;
    cursor: pointer;

    img {
      filter: drop-shadow(-100px 0 0 #888);
      transform: translateX(100px);
    }

    &:hover img {
      filter: drop-shadow(-100px 0 0 #3385ff);
    }
  }
}
</style>
